package com.msti.controller;
import com.msti.entity.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.msti.service.LoginDAO;
import com.msti.service.LoginDAOImpl;
import com.msti.service.StudentDAO;
import com.msti.service.StudentDAOImpl;

/**
 * Servlet implementation class CheckLogin
 */
public class CheckLogin extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CheckLogin() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Employee employee = new Employee();
		employee.setUsername(request.getParameter("username"));
		employee.setPassword(request.getParameter("password"));
		LoginDAO loginDAO = new LoginDAOImpl();
		employee = loginDAO.getAuthentication(employee);
		String pageName = "errorLogin.jsp";
		if(employee != null && employee.getRole().equals("Accountant")){
			StudentDAO studentDAO = new StudentDAOImpl();
			List<Student> allUnConStudent = new ArrayList<Student>();
			allUnConStudent = studentDAO.getAllUnConfirmedStudent();
			request.setAttribute("allUnConStudent", allUnConStudent);
			pageName = "registrationConfirmation.jsp";
		}else if (employee != null && employee.getRole().equals("Administrator")) {
			pageName = "adminPage.jsp";
		}else {
			pageName = "login.jsp";
			request.setAttribute("errMsg", "Invalid Username or Password");
		}
		HttpSession session = request.getSession();
		session.setAttribute("user", employee);
		//response.sendRedirect(pageName);
		RequestDispatcher requestDispatcher = request.getRequestDispatcher(pageName);
		requestDispatcher.forward(request, response);
	}

}
